package com.lingjtx.common.pay;

import com.lingjtx.common.pay.common.PayChannelEnum;
import com.lingjtx.common.pay.handle.PayHandler;
import com.lingjtx.common.pay.model.NotifyEntity;
import com.lingjtx.common.pay.model.OrderEntity;
import com.lingjtx.common.pay.model.RefundEntity;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PayCenter {

    private final Map<PayChannelEnum, PayHandler> PAY_MAP = new HashMap<>();

    public PayCenter(@Qualifier("wePayService") PayHandler wePayService,
                     @Qualifier("aliPayService") PayHandler aliPayService) {
        PAY_MAP.put(PayChannelEnum.WECHAT, wePayService);
        PAY_MAP.put(PayChannelEnum.ALIPAY, aliPayService);
    }

    public PayHandler getPayService(PayChannelEnum type) {
        return PAY_MAP.get(type);
    }

    // 下单支付
    public Object pay(OrderEntity order) {
        PayHandler payService = getPayService(order.getType());
        return switch (order.getPayScene()) {
            case APP -> payService.appOrder(order);
            case H5 -> payService.h5Order(order);
            case MINI_PROGRAM -> payService.miniProgramOrder(order);
            case QR_CODE -> payService.nativeOrder(order);
        };
    }

    // 退款申请
    public Object refunds(RefundEntity model) {
        PayHandler payService = getPayService(model.getType());
        return payService.refunds(model);
    }

    // 关闭订单：当用户操作取消订单时调用此方法
    public void closeOrder(PayChannelEnum type, String orderNo) {
        PayHandler payService = getPayService(type);
        payService.closeOrder(orderNo);
    }

    // 获取订单详情
    public Object getOrderDetail(PayChannelEnum type, String orderNo) {
        PayHandler payService = getPayService(type);
        return payService.getOrderDetail(orderNo);
    }

    // 支付-退款回调通知
    public NotifyEntity callbackNotify(PayChannelEnum type, String data) {
        PayHandler payService = getPayService(type);
        return payService.handle(data);
    }
}
